﻿$(function () {
    $("#goodsGrid").Grid({
        url: '../goods/list',
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {
                label: '来源', name: 'agentGoodsId', index: 'agent_goods_id', width: 50,
                formatter: function (value) {
                    return value ? '<span class="label label-danger">代理</span>': '<span class="label label-success">自有</span>';
                }
            },
            {label: '商品类型', name: 'categoryName', index: 'category_id', width: 80},
            {label: '商品名称', name: 'name', index: 'name', width: 160},
            {label: '商品编码', name: 'goodsSn', index: 'goods_sn', width: 80},
            {
                label: '允许代理', name: 'isAllowAgent', index: 'is_allow_agent', width: 50, align: 'center',
                formatter: function (value) {
                    return transIsNot(value);
                }
            },
            {
                label: '上架', name: 'isOnSale', index: 'is_on_sale', width: 35, align: 'center',
                formatter: function (value) {
                    return transIsNot(value);
                }
            },
            {
                label: '热销', name: 'isHot', index: 'is_hot', width: 35, align: 'center', formatter: function (value) {
                    return transIsNot(value);
                }
            },
            {label: '销售类型', name: 'saleType', index: 'sale_type', width: 50, align: 'center', formatter: function (value) {
                    switch(value){
                        case 'x':
                            return '现货';
                            break;

                        case 'q':
                            return '订货';
                            break;

                        case 'p':
                            return '拼单';
                            break;
                    }
                }
            },
            {label: '最低访问等级', name: 'accessUserGrade',index: 'access_user_grade', width: 60, align: 'center', formatter: function (value) {
                    switch(value){
                        case 0:
                            return '游客级';
                            break;

                        case 1:
                            return '普通客户级';
                            break;

                        case 2:
                            return '高级客户级';
                            break;
                    }
                }
            },
            {label: '定价策略', name: 'priceType', index: 'price_type', width: 60, align: 'center', formatter: function (value) {
                    switch(value){
                        case 0:
                            return '三级阶梯价格';
                            break;

                        case 1:
                            return '单一价格';
                            break;

                        case 2:
                            return '成本自动计价';
                            break;
                    }
                }
            },
            {label: '高级客户阶梯价格', name: 'vipClientPrice', index: 'vip_client_price', width: 80},
            {label: '高级客户成本计单价', name: 'singleThiPrice', index: 'single_thi_price', width: 80},
            {label: '高级客户零售价格', name: 'counterThiPrice', index: 'counter_thi_price', width: 80},
            {label: '总销售量', name: 'sellVolume', index: 'sell_volume', width: 80}
        ]
    });
    $('#goodsDesc').editable({
        inlineMode: false,
        alwaysBlank: true,
        height: '500px', //高度
        minHeight: '200px',
        language: "zh_cn",
        spellcheck: false,
        plainPaste: true,
        enableScript: false,
        imageButtons: ["floatImageLeft", "floatImageNone", "floatImageRight", "linkImage", "replaceImage", "removeImage"],
        allowedImageTypes: ["jpeg", "jpg", "png", "gif"],
        imageUploadURL: '../sys/oss/upload',
        imageUploadParams: {id: "edit"},
        imagesLoadURL: '../sys/oss/queryAll'
    });


    $("#goodsSpecificationGrid").Grid({
        url: '../goodsspecification/list',
        shrinkToFit: true,
        width: 1000,
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '规格项', name: 'specificationName', index: 'specification_id', width: 300},
            {label: '规格值', name: 'value', index: 'value', width: 300},
            {
                label: '规格图片', name: 'picUrl', index: 'pic_url', width: 200, formatter: function (value) {
                    return transImg(value);
                }
            }]
    });
    $("#goodsSpecificationGrid").setGridWidth($(window).width()-40);

    $("#productGrid").Grid({
        url: '../product/list',
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '商品序列号', name: 'goodsSn', index: 'goods_sn', width: 80},
            {
                label: '商品规格',
                name: 'specificationsName',
                index: 'goods_specification_ids',
                width: 100,
                formatter: function (value, options, row) {
                    return value.replace(row.goodsName + " ", '');
                }
            },
            {label: '商品库存数', name: 'goodsNumber', index: 'goods_number', width: 80}]
    });
    $("#productGrid").setGridWidth($(window).width()-40);

});

//var ztree;

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};

var vm = new Vue({
    el: '#rrapp',
    data: {
        showGoodsList: true,
        title: '', //商品标题
        titleGoodsspecification: '', //商品规格标题
        showGoodsspecificationModal: false, //显示商品规格窗口
        titleProduct: '', //商品库存标题
        showProductModal: false, //显示商品库存窗口
        uploadList: [],
        imgName: '',
        visible: false,
        currShop: {},
        goods: {},
        goodsSpecification: {}, //当前商品规格详情，含规格项和规格值
        specifications: [], //所有配置的规格项
        product: {}, //当前商品库存详情
        productOpsType: '', //判断是新增还是修改操作
        productSelectedSpecification: [], //商品库存详情选中的商品规格（规格项+"#"+规格值）
        productSpecifications: [], //规格项列表，中大团队扩展
        productSpecificationItems: [], //所有规格项的下拉列表，中大团队扩展
        productCheckedSpecificationsStr: '#',   //用于记录已经选择过的规格，以#进行分割，中大团队扩展
        productPartSpecifications: [],  //选中的多个规格项
        ruleValidate: {
            saleType: [
                {required: true, message:'销售类型不能为空', trigger:'blur'}
            ],
            goodsSn: [
                {required: true, message:'商品编码不能为空', trigger:'blur'}
            ],
            name: [
                {required: true, message:'商品名称不能为空', trigger:'blur'}
            ],
            futuresListingDate: [
                {required: true, message:'期货上市日期不能为空', trigger:'blur'}
            ],
            accessUserGrade: [
                {required: true, validator:validateZeroToTwo, trigger:'blur'}
            ],
            priceType: [
                {required: true, validator:validateZeroToTwo, trigger:'blur'}
            ],
            counterPrice: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            counterSecPrice: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            counterThiPrice: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            retailPrice: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            clientPrice: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            vipClientPrice: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            firstNum: [
                {required: true, validator:validateInteger, trigger:'blur'}
            ],
            firstDiscount: [
                {required: true, validator:validatePercent, trigger:'blur'}
            ],
            secondNum: [
                {required: true, validator:validateInteger, trigger:'blur'}
            ],
            secondDiscount: [
                {required: true, validator:validatePercent, trigger:'blur'}
            ],
            collageMiniNum: [
                {required: true, validator:validateInteger, trigger:'blur'}
            ],
            singleShareCost: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            singleMakeCost: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            singleOrderCost: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            singleProfitCost: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            singlePrice: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            singleSecPrice: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            singleThiPrice: [
                {required: true, validator:validateNumber, trigger:'blur'}
            ],
            isAllowAgent: [
                {required: true, validator:validateBoolean, trigger:'blur'}
            ],
            isOnSale: [
                {required: true, validator:validateBoolean, trigger:'blur'}
            ],
            isNew: [
                {required: true, validator:validateBoolean, trigger:'blur'}
            ],
            isHot: [
                {required: true, validator:validateBoolean, trigger:'blur'}
            ],
            sortOrder: [
                {required: true, validator:validateInteger, trigger:'blur'}
            ]
        },
        q: {
            goodsSn: '',
            name: ''
        },
        categoryNames: [],
        categories: [],
        brands: [],//品牌
        macros: [],//商品单位
        attributeCategories: [],//属性类别
        currentStep: 0
    },
    methods: {
        selectStep0: function () {
            vm.currentStep = 0;
        },
        selectStep1: function () {
            vm.currentStep = 1;
        },
        selectStep2: function () {
            vm.currentStep = 2;
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showGoodsList = false;
            vm.title = "新增";
            vm.uploadList = [];
            vm.newGoods();
            $('#goodsDesc').editable('setHTML', '');
            //vm.getCategory();
            vm.categoryNames = [];
            vm.brands = [];
            vm.macros = [];
            vm.attributeCategories = [];
            // vm.attribute = [];
            vm.getCategories();
            //vm.getBrands();
            //vm.getMacro();
            //vm.getAttributeCategories();
            // vm.getAttributes('');

            vm.goodsSpecification = {};
            vm.specifications = [];
            vm.product = {};
            vm.productOpsType = '';
            vm.productSelectedSpecification = [];
            vm.productSpecifications = [];
            vm.productSpecificationItems = [];
            vm.productPartSpecifications = [];

            vm.loadGoodsSpecificationGrid('null');
            vm.loadProductGrid('null');
        },
        update: function (event) {
            var id = getSelectedRow("#goodsGrid");
            if (id == null) {
                return;
            }
            vm.showGoodsList = false;
            vm.title = "修改";
            vm.uploadList = [];
            vm.categoryNames = [];
            vm.getCategories();
            vm.getInfo(id);
            //vm.getBrands();
            //vm.getMacro();
            //vm.getAttributeCategories();
            vm.getGoodsGallery(id);
            vm.loadGoodsSpecificationGrid(id);
            vm.loadProductGrid(id);
        },
        loadGoodsSpecificationGrid: function (id) {
            vm.showGoodsspecificationModal = false;
            var page = $("#goodsSpecificationGrid").jqGrid('getGridParam', 'page');
            $("#goodsSpecificationGrid").jqGrid('setGridParam', {
                postData: {'goodsId': id},
                page: page
            }).trigger("reloadGrid");
        },
        reloadGoodsSpecificationGrid: function () {
            vm.loadGoodsSpecificationGrid(vm.goods.id);
        },
        loadProductGrid: function (id) {
            vm.showProductModal = false;
            var page = $("#productGrid").jqGrid('getGridParam', 'page');
            $("#productGrid").jqGrid('setGridParam', {
                postData: {'goodsId': id},
                page: page
            }).trigger("reloadGrid");
        },
        reloadProductGrid: function () {
            vm.loadProductGrid(vm.goods.id);
        },
        addGoodsspecification: function () {
            if(!vm.goods.id){
                alert("请先填写商品信息并提交，然后再进行规格设置！");
                return;
            }

            vm.showGoodsspecificationModal = true;
            vm.titleGoodsspecification = "新增规格设置";
            vm.goodsSpecification = {};
            vm.getSpecifications();
        },
        getSpecifications: function () {
            Ajax.request({
                url: "../specification/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.specifications = r.list;
                }
            });
        },
        updateGoodsspecification: function (event) {
            var id = getSelectedRow("#goodsSpecificationGrid");
            if (id == null) {
                return;
            }
            vm.showGoodsspecificationModal = true;
            vm.titleGoodsspecification = "修改规格设置";
            vm.getGoodsspecificationInfo(id);
        },
        getGoodsspecificationInfo: function (id) {
            Ajax.request({
                url: "../goodsspecification/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.goodsSpecification = r.goodsSpecification;
                    vm.getSpecifications();
                }
            });
        },
        delGoodsspecification: function (event) {
            var ids = getSelectedRows("#goodsSpecificationGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../goodsspecification/delete",
                    contentType: "application/json",
                    params: JSON.stringify(ids),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reloadGoodsSpecificationGrid();
                        });
                    }
                });

            });
        },
        handleGoodsspecificationSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdateGoodsspecification();
            });
        },
        saveOrUpdateGoodsspecification: function (event) {
            vm.goodsSpecification.goodsId = vm.goods.id;
            var url = vm.goodsSpecification.id == null ? "../goodsspecification/save" : "../goodsspecification/update";

            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.goodsSpecification),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reloadGoodsSpecificationGrid();
                    });
                }
            });
        },
        addProduct: function () {
            if(!vm.goods.id){
                alert("请先填写商品信息并提交，然后再进行库存设置！");
                return;
            }

            vm.showProductModal = true;
            vm.titleProduct = "新增库存设置";
            vm.product = {};
            vm.productOpsType = 'add';
            //vm.clearProductFormState();

            Ajax.request({
                url: "../goods/info/" + vm.goods.id,
                async: true,
                successCallback: function (r) {
                    //if (vm.type == 'add') {
                    //    vm.product.goodsSn = r.goods.goodsSn;
                    //    vm.product.goodsNumber = r.goods.goodsNumber;
                    //    vm.product.retailPrice = r.goods.retailPrice;
                    //    vm.product.marketPrice = r.goods.marketPrice;
                    //}

                    //默认
                    vm.product.goodsId = vm.goods.id;
                    vm.product.goodsNumber = 0;

                    //中大团队扩展，动态获取商品规格配置
                    Ajax.request({
                        url: "../specification/getSpecificationsByGoodsId?goodsId="+vm.goods.id,
                        async: true,
                        successCallback: function (r) {
                            vm.productSpecifications = r.list;
                            vm.clearProductFormState();
                        }
                    });
                }
            });
        },
        updateProduct: function (event) {
            let id = getSelectedRow("#productGrid");
            if (id == null) {
                return;
            }
            vm.showProductModal = true;
            vm.titleProduct = "修改库存设置";
            vm.productOpsType = 'update';
            vm.clearProductFormState();
            vm.getProductInfo(id);
        },
        delProduct: function (event) {
            let ids = getSelectedRows("#productGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../product/delete",
                    contentType: "application/json",
                    params: JSON.stringify(ids),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reloadProductGrid();
                        });
                    }
                });
            });
        },
        handleProductSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdateProduct()
            });
        },
        saveOrUpdateProduct: function (event) {
            let url = vm.product.id == null ? "../product/save" : "../product/update";

            //检查库存数
            if(!vm.product.goodsSn || vm.product.goodsSn.length == 0){
                alert("商品序列号不能为空，请填写！");
                return;
            }

            //检查库存数
            if(!vm.product.goodsNumber || vm.product.goodsNumber == 0){
                alert("库存设置不正确，请选择所有规格后再录入大于零的库存数！");
                return;
            }

            //计算规格字符串
            var goodsSpecificationIds = "";
            if(vm.productPartSpecifications && vm.productPartSpecifications.length > 0){
                for(var i=0; i<vm.productPartSpecifications.length; i++){
                    goodsSpecificationIds += vm.productPartSpecifications[i] + "_";
                }
                vm.product.goodsSpecificationIds = goodsSpecificationIds;
            }

            //提交表单数据
            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.product),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reloadProductGrid();
                    });
                }
            });
        },
        clearProductFormState: function(){
            //清空相关状态值
            vm.productSelectedSpecification = [];
            vm.productSpecificationItems = [];
            vm.productCheckedSpecificationsStr = "";
            vm.productPartSpecifications = [];
        },
        getProductInfo: function (id) {
            Ajax.request({
                url: "../product/getInfoDetail/" + id,
                async: true,
                successCallback: function (r) {
                    vm.product = r.product;
                }
            });
        },
        getProductSpecificationItems: function(data) {
            if(data.length > 0){
                //需要获取下拉列表的规格项
                var specificationId;
                var idx = 0;

                for(var i=0; i<data.length; i++) {
                    if(vm.productSelectedSpecification.indexOf("#"+data[i]+"#") < 0) {
                        specificationId = data[i];
                        idx = i;
                        vm.productCheckedSpecificationsStr += data[i] + "#";
                    }
                }

                if(specificationId) {
                    Ajax.request({
                        url: "../goodsspecification/queryAll?goodsId=" + vm.goods.id + "&specificationId=" + specificationId,
                        async: true,
                        successCallback: function (r) {
                            vm.productSpecificationItems[idx] = r.list;

                            //更改并复原selectedSpecification值，触发页面下拉框刷新
                            var copy = vm.productSelectedSpecification.slice(0);
                            vm.productSelectedSpecification = [];
                            vm.productSelectedSpecification = copy;
                        }
                    });
                }
            }
        },
        newGoods: function() {
            Ajax.request({
                url: "../goods/newGoods",
                async: true,
                successCallback: function (r) {
                    vm.goods = r.goods;
                    vm.currShop = r.currShop;
                }
            });
        },
        getCategories: function() {
            Ajax.request({
                url: "../category/queryAllSecond",
                async: true,
                successCallback: function(r) {
                    vm.categories = r.list;
                }
            });
        },
        /**
         * 获取品牌
         */
        getBrands: function () {
            Ajax.request({
                url: "../brand/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.brands = r.list;
                }
            });
        },
        /**
         * 获取单位
         */
        getMacro: function () {
            Ajax.request({
                url: "../sys/macro/queryMacrosByValue?value=goodsUnit",
                async: true,
                successCallback: function (r) {
                    vm.macros = r.list;
                }
            });
        },
        /**
         * 获取会员等级，中大拓展团队
         */
        //getUserLevels: function () {
        //   Ajax.request({
        //       url: "../userlevel/queryAll",
        //        async: true,
        //        successCallback: function (r) {
        //            vm.userLevels = r.list;
        //        }
        //    });
        //},
        getGoodsGallery: function (id) {//获取商品顶部轮播图
            Ajax.request({
                url: "../goodsgallery/queryAll?goodsId=" + id,
                async: true,
                successCallback: function (r) {
                    vm.uploadList = r.list;
                }
            });
        },
        getAttributeCategories: function () {
            Ajax.request({
                url: "../attributecategory/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.attributeCategories = r.list;
                }
            });
        },
        saveOrUpdateAndNext: function (event) {
            var url = vm.goods.id == null ? "../goods/save" : "../goods/update";

            vm.goods.goodsDesc = $('#goodsDesc').editable('getHTML');
            vm.goods.goodsImgList = vm.uploadList;
            var Str = "";
            for(var i = 0; i < vm.categoryNames.length; i++){
                Str += vm.categoryNames[i] + "#";
            }
            vm.goods.categoryIds = Str.substring(0, Str.length - 1);

            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.goods),
                successCallback: function (r) {
                    //新增要保存商品ID，然后才可以下一步操作
                    if(r.goodsId){
                        vm.goods.id = r.goodsId;
                    }

                    alert('操作成功', function (index) {
                        vm.selectStep1();
                    });
                }
            });
        },
        enSale: function () {
            var id = getSelectedRow("#goodsGrid");
            if (id == null) {
                return;
            }
            confirm('确定要上架选中的商品？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../goods/enSale",
                    params: JSON.stringify(id),
                    contentType: "application/json",
                    type: 'POST',
                    successCallback: function () {
                        alert('提交成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        openSpe: function () {
            var id = getSelectedRow("#goodsGrid");
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '商品规格',
                content: '../shop/goodsspecification.html?goodsId=' + id
            })
        },
        openPro: function () {
            var id = getSelectedRow("#goodsGrid");
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '产品设置',
                content: '../shop/product.html?goodsId=' + id
            });
        },
        unSale: function () {
            var id = getSelectedRow("#goodsGrid");
            if (id == null) {
                return;
            }
            confirm('确定要下架选中的商品？', function () {

                Ajax.request({
                    type: "POST",
                    url: "../goods/unSale",
                    contentType: "application/json",
                    params: JSON.stringify(id),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();;
                        });
                    }
                });

            });
        },
        del: function (event) {
            var ids = getSelectedRows("#goodsGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../goods/delete",
                    contentType: "application/json",
                    params: JSON.stringify(ids),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();;
                        });
                    }
                });

            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../goods/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.goods = r.goods;
                    vm.currShop = r.currShop;
                    vm.categoryNames = r.categoryIds;
                    $('#goodsDesc').editable('setHTML', vm.goods.goodsDesc);
                    //vm.getCategory();
                }
            });
        },
        reload: function (event) {
            vm.showGoodsList = true;
            var page = $("#goodsGrid").jqGrid('getGridParam', 'page');
            $("#goodsGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        /*getCategory: function () {
            //加载分类树
            Ajax.request({
                url: "../category/queryAll",
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                    var node = ztree.getNodeByParam("id", vm.goods.categoryId);
                    if (node) {
                        ztree.selectNode(node);
                        vm.goods.categoryName = node.name;
                    } else {
                        node = ztree.getNodeByParam("id", 0);
                        ztree.selectNode(node);
                        vm.goods.categoryName = node.name;
                    }
                }
            });
        },
        categoryTree: function () {
            openWindow({
                title: "选择类型",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级菜单
                    vm.goods.categoryId = node[0].id;
                    vm.goods.categoryName = node[0].name;

                    layer.close(index);
                }
            });
        },*/
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove(file) {
            // 从 upload 实例删除数据
            const fileList = this.uploadList;
            this.uploadList.splice(fileList.indexOf(file), 1);
        },
        handleSuccess(res, file) {
            //计算排序号，文件名必须为：P#1.jpg
            var sortOrder = 10;
            file.name = file.name.substring(0, file.name.indexOf("."));
            var pos = file.name.indexOf("#");
            if(pos > 0){
                sortOrder = parseInt(file.name.substring(pos+1, file.name.length));
                sortOrder = sortOrder > 10 ? 10 : sortOrder;
            }
            file.sortOrder = sortOrder;

            file.imgUrl = res.url;
            file.name = res.url;

            vm.uploadList.add(file);
            vm.uploadList.sort(vm.uploadListSort);
        },
        handleGoodsSpecificationSuccess(res, file) {
            vm.goodsSpecification.picUrl = file.response.url;
        },
        handleGoodsSpecificationFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleGoodsSpecificationMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        eyeGoodsSpecificationImage: function () {
            var url = vm.goodsSpecification.picUrl;
            eyeImage(url);
        },
        uploadListSort: function(a, b) {
            return a.sortOrder > b.sortOrder;
        },
        handleBeforeUpload() {
            const check = this.uploadList.length < 10;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 10 张图片。'
                });
            }
            return check;
        },
        handleSubmitAndNext: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdateAndNext()
            });
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
            return false;
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 256K。'
            });
            return false;
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleSuccessPicUrl: function (res, file) {
            vm.goods.primaryPicUrl = file.response.url;
        },
        handleSuccessListPicUrl: function (res, file) {
            vm.goods.listPicUrl = file.response.url;
        },
        eyeImagePicUrl: function () {
            var url = vm.goods.primaryPicUrl;
            eyeImage(url);
        },
        eyeImageListPicUrl: function () {
            var url = vm.goods.listPicUrl;
            eyeImage(url);
        },
        eyeImage: function (e) {
            eyeImage($(e.target).attr('src'));
        },
        calcSinglePrice: function () {
            var singleShareCost = parseFloat(vm.goods.singleShareCost);
            var singleMakeCost = parseFloat(vm.goods.singleMakeCost);
            var singleOrderCost = parseFloat(vm.goods.singleOrderCost);
            var singleProfitCost = parseFloat(vm.goods.singleProfitCost);
            var firstDiscount = parseFloat(vm.goods.firstDiscount);
            var secondDiscount = parseFloat(vm.goods.secondDiscount);

            if(singleShareCost && singleMakeCost && singleOrderCost && singleProfitCost){
                vm.goods.singlePrice = singleShareCost + singleMakeCost + singleOrderCost + singleProfitCost;

                if(firstDiscount){
                    vm.goods.singleSecPrice = singleShareCost + singleMakeCost + singleOrderCost + singleProfitCost * firstDiscount;
                }
                if(secondDiscount){
                    vm.goods.singleThiPrice = singleShareCost + singleMakeCost + singleOrderCost + singleProfitCost * secondDiscount;
                }
            }
        }
    },
    mounted() {
        this.uploadList = this.$refs.upload.fileList;
    }
});